package com.sz.stock.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sz.stock.client.MarketClient;
import com.sz.stock.client.TradingClient;
import com.sz.stock.client.UserClient;
import com.sz.stock.common.ResultBean;
import com.sz.stock.model.*;
import javafx.geometry.Pos;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;

import static java.math.BigDecimal.ROUND_DOWN;

@RestController
@RequestMapping("/trad")
public class BuyController {

    @Autowired
    private MarketClient marketClient;
    @Autowired
    private TradingClient tradingClient;
    @Autowired
    private UserClient userClient;

    //1. 查询一支 股票.(查询 股票名称 需要T_Stock表数据)
    @RequestMapping("/stock/getStock")
    public ResultBean getStock(@RequestBody String code) {
        System.out.println("查询一只股票 code====>>" + code);
        return marketClient.getStock(code);
    }

    //2. 查询 一支股票   涨停和跌停  价格  返回给页面测试用 ( 需要 StopPoint 表数据 )
    @RequestMapping("/stock/getOnePoint")
    public ResultBean getOnePoint(@RequestBody String code) {
        return marketClient.getOneStopPoint(code);
    }


    //2.1 查询 一支股票   涨停  价格 ( 需要 StopPoint 表数据 )
    @RequestMapping("/stock/getOneStopPoint")
    public BigDecimal getOneStopPoint(@RequestBody String code) {
        ResultBean oneStopPoint = marketClient.getOneStopPoint(code);
        Object data = oneStopPoint.getData();
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(data));
        Object stockRMax = jsonObject.get("stockRMax");
        BigDecimal stockMax = new BigDecimal(stockRMax.toString());
        System.out.println("stockMax====>>" + stockMax);
        return stockMax;
    }

    //2.1 查询 一支股票  跌停  价格 ( 需要 StopPoint 表数据 )
    @RequestMapping("/stock/getOneUpPoint")
    public BigDecimal getOneUpPoint(@RequestBody String code) {
        ResultBean oneStopPoint = marketClient.getOneStopPoint(code);
        Object data = oneStopPoint.getData();
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(data));
        Object stockFMix = jsonObject.get("stockFMix");
        BigDecimal stockMix = new BigDecimal(stockFMix.toString());
        System.out.println("stockMax====>>" + stockMix);
        return stockMix;
    }

    // 3. 查询一支股票的最新价格 ( 需要 OHLC 表数据 )
    @RequestMapping("/stock/getOneOhcl")
    public ResultBean getOneOhcl(@RequestBody String code) {
        return marketClient.getOneOhcl(code);
    }

    //3. 计算出可以购买股票的数量Amount
    @RequestMapping("/getAmount")
    public ResultBean getAmount(@RequestBody Entrust entrust) {

            System.out.println("委托对象=="+entrust);
            System.out.println("用户的ID =="+entrust.getStockEntrustUserid());
            TUser tUser = selectTUserByUserID(entrust.getStockEntrustUserid());
            // 用户的资金 userBalance
            BigDecimal userBalance = tUser.getUserbalance();

            BigDecimal result = userBalance.divide(entrust.getStockEntrustMoney(), 0, ROUND_DOWN);
            BigDecimal num = new BigDecimal("100");
            BigDecimal a = result.divide(num, 0, ROUND_DOWN);
            //a 转为 int 类型
            int entrustAmount1 = a.intValue();
            int entrustAmount = entrustAmount1 * 100;
            return new ResultBean(101, "计算出可买入的股票数量", entrustAmount);

    }

    //4. 提交买入.存入委托 更新买卖盘信息
    @RequestMapping("/buy/addEntrust")
    public ResultBean addEntrustForBuy(@RequestBody(required = false) Entrust entrust) {
//        System.out.println("存入委托 code====>" + entrust.getStockEntrustCode());
//        System.out.println("存入委托 company====>" + entrust.getStockEntrustCompany());
//        System.out.println("存入委托 num====>" + entrust.getStockEntrustNum());
//        System.out.println("存入委托 money====>" + entrust.getStockEntrustMoney());
//
        System.out.println(entrust);

        ResultBean resultBean = tradingClient.addEntrustForBuy(entrust);
        String data = resultBean.getData().toString();
        //这样得到的 Entrust 有 主键ID
        Entrust entrust1 = selectEntrustByContractID(data);
        System.out.println("entrust1 = " + entrust1);
         /*
         ======== 用户 金额 的修改 ======
         */
        System.out.println("===== 用户 金额 的修改 ======");
        //得到 用户id
        Integer stockEntrustUserid = entrust1.getStockEntrustUserid();
        System.out.println("stockEntrustUserid = " + stockEntrustUserid);
        //得到 委托金额
        BigDecimal stockEntrustMoney = entrust1.getStockEntrustMoney();
        System.out.println("stockEntrustMoney = " + stockEntrustMoney);
        //得到 委托数量(int)转换成 String 为了后面装换成 BigDecimal
        String s = entrust1.getStockEntrustNum().toString();
        System.out.println("s = " + s);
        // 将委托数量 转换 成 BigDecimal
        BigDecimal stockEntrustNum = new BigDecimal(s);
        System.out.println("stockEntrustNum = " + stockEntrustNum);
        // 委托数量 * 委托金额 = 需要扣除用户的金额
        BigDecimal sumBalance = stockEntrustMoney.multiply(stockEntrustNum);
        System.out.println("sumBalance = " + sumBalance);

        TUser tUser = selectTUserByUserID(stockEntrustUserid);
        System.out.println("余额前=="+tUser.getUserbalance());
        // 扣除金额的方法 需要传入 (用户id, 需要扣除的金额)
        withdraw(stockEntrustUserid,sumBalance);
        System.out.println("余额后=="+tUser.getUserbalance());
        System.out.println("===== 用户 金额 的修改 ======");
        //判断是否能成交
        selectSellEntrust(data);

        return resultBean;

    }


    //5. 买入数量 的判断.(不能大于可买数量)
    @RequestMapping("/getNum")
    public ResultBean getNum(@RequestBody Entrust entrust) {
        String data = null;
        Integer stockEntrustNum = entrust.getStockEntrustNum();
        Integer stockEntrustAmount = entrust.getStockEntrustAmount();
        if (stockEntrustNum > stockEntrustAmount) {
            data = "买入数量不能大于可买数量!";
            return new ResultBean(444, "委托数量输入错误", data);
        } else {
            return new ResultBean(101, "委托数量输入正确", data);
        }
    }

    //6. 查询委托信息
    @RequestMapping("/trading/showEntrust")
    public ResultBean showEntrust(int userid) {
        return tradingClient.showEntrust(userid);

    }

    //6.1 查询委托信息.通过userid
    @RequestMapping("/showE")
    public ResultBean showE(@RequestBody Entrust entrust) {
        System.out.println("进入 查询委托信息!!!!!!!!");
        //从redis中取出 userid
        int userid = entrust.getStockEntrustUserid();
        if (userid == 0) {
            //没有登录.回登录页面去
            return new ResultBean(444, "请先登录!", null);
        } else {
            System.out.println(userid);
            return tradingClient.showEntrust(userid);
        }
    }

    @RequestMapping("/bos/getfive")
    public ResultBean getFive(@RequestParam(value = "code", required = false) String code, @RequestParam(value = "type", required = false) String type) {
        System.out.println("code = " + code);
        System.out.println("type = " + type);
        return tradingClient.getFive(code, type);
    }


    //7. 将交易成功的买入委托加入到持仓表中
    @RequestMapping("/buy/addPOSForBuy")
    public ResultBean addPOS(POS pos) {
        return tradingClient.addPosForBuy(pos);
    }

    //8. 添加 成交表
    @RequestMapping("/buy/addDeal")
    public ResultBean addDeal(Deal deal) {
        return tradingClient.addDeal(deal);
    }

    //9. 判断 委托是否可以成交
    @RequestMapping("/buy/selectSellEntrust")
    public ResultBean selectSellEntrust(@RequestParam(value = "stockEntrustContractid") String stockEntrustContractid) {

        //这样得到的 Entrust 有 主键ID
        Entrust entrust1 = selectEntrustByContractID(stockEntrustContractid);
        System.out.println("entrust1 = " + entrust1);

        System.out.println("进入了 判断成交的方法了!!!进入了 判断成交的方法了!!!进入了 判断成交的方法了!!!");
        System.out.println("判断委托的对象传入进来了!!!!========" + entrust1);
        ResultBean r1 = null;
        //1. 得到股票的代码
        String stockEntrustCode = entrust1.getStockEntrustCode();
        //2. 得到委托买入的价格
        BigDecimal stockEntrustMoney = entrust1.getStockEntrustMoney();
        System.out.println("买入的委托价格 = " + stockEntrustMoney);
        /**
         * 3. 查找 卖出的委托信息(
         *     股票代码 == entrust.getStockEntrustCode()
         *     委托价格 <= entrust.getStockEntrustMoney()
         */
        if (tradingClient.selectSellEntrust(entrust1).getCode() == 0) {
            //没有能成交的委托信息
            return new ResultBean(0, "没有满足条件的委托信息", null);
        } else {
            //有可以成交的委托信息
            ResultBean resultBean = tradingClient.selectSellEntrust(entrust1);
            String jsonString = JSON.toJSONString(resultBean.getData());
            JSONArray jsonArray = JSONArray.parseArray(jsonString);
            System.out.println("json=====>>>>" + jsonArray);
            //int count = 0;
            int i1 = jsonArray.size();
            System.out.println("一共可交易的卖出委托数量" + i1);
            for (int i = 0; i < i1; i++) {
                System.out.println("==========第" + (i + 1) + "个委托信息!!!!!!");
                //   jsonArray.get(i) --> 查出的第i个卖出的委托信息

                // 第i个 卖出的委托数量
                Integer n1 = Integer.parseInt(jsonArray.getJSONObject(i).get("stockEntrustNum").toString());


                 /*
                ==========0. 一些要用到的信息==========
                */

                //2. 卖出委托的一些信息
                Integer SellEntrustId = Integer.parseInt(jsonArray.getJSONObject(i).get("stockEntrustId").toString());
                System.out.println("卖出委托的ID = " + SellEntrustId);
                BigDecimal sellEntrustMoney = new BigDecimal(jsonArray.getJSONObject(i).get("stockEntrustMoney").toString());
                System.out.println("卖出委托的价格 = " + sellEntrustMoney);
                Entrust sellEntrust = tradingClient.getOneEntrust(SellEntrustId);
                System.out.println("该卖出委托的对象 === " + sellEntrust);
                /*
                ======================================
                 */

                System.out.println("买入委托的总数量====>>>" + entrust1.getStockEntrustNum());
                int stockEntrustNum = entrust1.getStockEntrustNum();
                int stockEntrustTransnum = entrust1.getStockEntrustTransnum();
                int num = stockEntrustNum - stockEntrustTransnum;
                System.out.println("买入委托中 已成交的股票数量===>" + stockEntrustTransnum);
                System.out.println("买入的委托数量===" + num);
                int n = n1 - sellEntrust.getStockEntrustTransnum();
                System.out.println("卖出委托的数量=======>>" + n);
                // if(买入的委托数<卖出的委托数)
                if (num < n) {
                    /**
                     *  买入 < 卖出(买入委托-->全部成交; 卖出委托:-->部分成交; 持仓(卖出股票)数量-成交数量)
                     */
                    System.out.println("===================买入 < 卖出=================");
                    //卖出委托剩余可交易的数量
                    int canSellNum = sellEntrust.getStockEntrustNum() - sellEntrust.getStockEntrustTransnum();
                    //买入委托剩余可交易的数量
                    Integer canBuyNum1 = entrust1.getStockEntrustNum() - entrust1.getStockEntrustTransnum();
                    int canBuyNum = entrust1.getStockEntrustNum() - entrust1.getStockEntrustTransnum();
                    /*
                    ==========1. 修改委托表信息==========
                     */
                    //1. 将买入的状态改成全部成交
                    entrust1.setStockEntrustStatus("全部成交");

                    //2. 将买入的成交数量 改成 买入委托数量
                    entrust1.setStockEntrustTransnum(entrust1.getStockEntrustTransnum() + canBuyNum);

                    //(测试用) 修改后的 买入委托对象
                    System.out.println("修改后买入的委托对象====>>>" + entrust1);

                    // 修改买入委托数据库信息
                    updateEntrust(entrust1);

                    //3. 将卖出的状态改成 部成
                    sellEntrust.setStockEntrustStatus("部成");

                    //4. 将卖出的成交数量 改成 买入委托数量
                    sellEntrust.setStockEntrustTransnum(sellEntrust.getStockEntrustTransnum() + canBuyNum);


                    //(测试用) 修改后的 卖出委托对象
                    System.out.println("修改后卖出的委托对象====>>>" + sellEntrust);

                    //修改卖出委托 数据库信息
                    updateEntrust(sellEntrust);

                    /*
                    ==========2. 修改持仓表信息==========
                     */
                    //1. 创建持仓表的对象
                    int stockPosUserid = entrust1.getStockEntrustUserid();              // 用户 id
                    String stockPosCode = entrust1.getStockEntrustCode();                // 股票代码
                    String stockPosCompany = entrust1.getStockEntrustCompany();          // 股票名称
                    int stockPosTradblance = entrust1.getStockEntrustTransnum();         // 股票股数(剩余多少股)
                    int stockPosKyblance = entrust1.getStockEntrustNum();                // 可用股数(可以使用多少股)
                    int stockPosDjblance = 0;                                            // 冻结股数
                    BigDecimal stockPosMoney = new BigDecimal(entrust1.getStockEntrustMoney().toString());
                    //BigDecimal stockPosMoney = new BigDecimal(jsonArray.getJSONObject(i).get("stockEntrustMoney").toString());
                    POS pos = new POS(null, stockPosUserid, stockPosCode, stockPosCompany, stockPosTradblance, stockPosKyblance, stockPosDjblance, stockPosMoney);


                    //1. (买入委托)判断 持仓表中是否有该股票信息   若有 修改信息  若没有 添加持仓表
                    salePos(entrust1, pos);

                    //2. (卖出委托)在持仓中将 冻结数量 - 委托数量 ; 股票数量 - 委托数量
                    POS onePos = tradingClient.getOnePos(entrust1.getStockEntrustCode(), sellEntrust.getStockEntrustUserid());             //得到卖出的持仓对象
                    System.out.println("修改前卖出的持仓对象===>> = " + onePos);
                    onePos.setStockPosDjblance(onePos.getStockPosDjblance() - canBuyNum);         //持仓表的冻结金额 - 买入委托数量(成交数量)
                    onePos.setStockPosTradblance(onePos.getStockPosTradblance() - canBuyNum);     //持仓表的股票数 - 买入的委托数(成交数量)

                    //(测试) 修改后的 卖出委托持仓中的对象
                    System.out.println("修改后卖出的持仓对象====>>>" + onePos);

                    //修改卖出持仓 数据库信息
                    updatePos(onePos);

                    /*
                    ==========3. 修改成交表信息==========
                     */

                    //1. 将 买入委托 加入成交表中

                    //得到 卖出的成交对象
                    Deal deal = new Deal(null,
                            sellEntrust.getStockEntrustUserid(),
                            stockEntrustCode,
                            stockPosCompany,
                            "买入",
                            stockEntrustMoney,
                            new SimpleDateFormat("yyy-MM-dd HH:mm:ss.SSS").format(new Timestamp(System.currentTimeMillis())),
                            "BtB" + new SimpleDateFormat("yyyMMddHHmmssSSS").format(new Timestamp(System.currentTimeMillis()))
                    );

                    // 将成交对象插入数据库中
                    ResultBean resultBean1 = addDeal(deal);

                    //

                    //2. 将卖出委托 加入成交表中

                    //卖出委托的 用户id
                    int sellEntrustUserid = Integer.parseInt(jsonArray.getJSONObject(i).get("stockEntrustUserid").toString());

                    //(测试) 卖出委托用户id
                    System.out.println("sellEntrustUserid = " + sellEntrustUserid);

                    //得到 卖出的成交对象
                    Deal deal1 = new Deal(null,
                            sellEntrustUserid,
                            stockPosCode,
                            stockPosCompany,
                            "卖出",
                            sellEntrustMoney,
                            new SimpleDateFormat("yyy-MM-dd HH:mm:ss.SSS").format(new Timestamp(System.currentTimeMillis())),
                            "StS" + new SimpleDateFormat("yyyMMddHHmmssSSS").format(new Timestamp(System.currentTimeMillis()))
                    );
                    /*
                     * ======== 用户 金额 的修改 ======
                     */
                    // 将成交对象插入数据库中
                    ResultBean resultBean2 = addDeal(deal1);
                    // 卖出用户的id
                    Integer sellID = sellEntrust.getStockEntrustUserid();
                    // 卖出的数量
                    String s = canBuyNum1.toString();
                    BigDecimal sellNum = new BigDecimal(s);
                    // 卖出的委托价格
                    BigDecimal stockEntrustMoney1 = sellEntrust.getStockEntrustMoney();
                    //总金额
                    BigDecimal sumBalance = sellNum.multiply(stockEntrustMoney1);
                    // 增加金额的方法
                    topup(sellID,sumBalance);

                    /*
                    * ======== 修改 买卖盘信息 =======
                    * */
                    //买盘的对象
                    StockBuyOrSale buyBos = selectBos(entrust1);
                    System.out.println("buyBos 前 = " + buyBos);
                    //修改买盘的数量
                    buyBos.setStockBSQuantity(buyBos.getStockBSQuantity()-canBuyNum);
                    System.out.println("buyBos 后 = " + buyBos);
                    //修改数据库信息
                    updateBos(buyBos);

                    //买盘的对象
                    StockBuyOrSale sellBos = selectBos(sellEntrust);
                    System.out.println("sellBos 前 = " + sellBos);
                    //修改买盘的数量
                    sellBos.setStockBSQuantity(sellBos.getStockBSQuantity()-canBuyNum);
                    System.out.println("sellBos 后 = " + sellBos);
                    //修改数据库信息
                    updateBos(sellBos);


                    // 7. 判断是否成功
                    if (resultBean1.getCode() == 1 && resultBean2.getCode() == 1) {
                        r1 = new ResultBean(1, "交易成功!", "成交完成!");
                    } else {
                        r1 = new ResultBean(0, "交易失败!", "成交失败!");
                    }

                    break;


                } else if (num == n) {
                    /**
                     *  买入等于卖出 (买入委托和卖出委托 -->>全部成交)
                     */
                    System.out.println("===================买入 = 卖出=================");
                    int sellEntrustUserid = Integer.parseInt(jsonArray.getJSONObject(i).get("stockEntrustUserid").toString());

                    buyEqualSell(entrust1, sellEntrust, sellEntrustUserid, sellEntrustMoney, r1);

                    break;

                } else if (num > n) {
                    /**
                     *  买入大于卖出 ()
                     */
                    System.out.println("===================买入 > 卖出=================");

                    int sellEntrustUserid = Integer.parseInt(jsonArray.getJSONObject(i).get("stockEntrustUserid").toString());
                    buyMoreSell(entrust1, sellEntrust, sellEntrustUserid, sellEntrustMoney, r1);

                }
            }
        }
        return r1;
    }

    //10. 当买入 大于 卖出
    public void buyMoreSell(Entrust entrust1, Entrust sellEntrust, int sellEntrustUserid, BigDecimal sellEntrustMoney, ResultBean r1) {
        System.out.println("当买入大于卖出是的Entrust==>>" + entrust1);
        System.out.println("当买入大于卖出是的SellEntrust==>>" + sellEntrust);
        //卖出委托剩余可交易的数量
        int canSellNum = sellEntrust.getStockEntrustNum() - sellEntrust.getStockEntrustTransnum();
        Integer canSellNum1 = sellEntrust.getStockEntrustNum() - sellEntrust.getStockEntrustTransnum();
        //买入委托剩余可交易的数量
        int canBuyNum = entrust1.getStockEntrustNum() - entrust1.getStockEntrustTransnum();
        Integer canBuyNum1 = entrust1.getStockEntrustNum() - entrust1.getStockEntrustTransnum();
          /*
          ==========1. 修改委托表信息==========
           */
        //1. 将买入的状态改成部成
        entrust1.setStockEntrustStatus("部成");

        //2. 将买入的成交数量 改成 卖出委托数量
        entrust1.setStockEntrustTransnum(canSellNum + entrust1.getStockEntrustTransnum());

        //(测试用) 修改后的 买入委托对象
        System.out.println("修改后买入的委托对象====>>>" + entrust1);

        // 修改买入委托数据库信息
        updateEntrust(entrust1);

        //3. 将卖出的状态改成 全部成交
        sellEntrust.setStockEntrustStatus("全部成交");

        //4. 将卖出的成交数量 改成 卖出委托数量+原有的成交数量
        sellEntrust.setStockEntrustTransnum(canSellNum + sellEntrust.getStockEntrustTransnum());


        //(测试用) 修改后的 卖出委托对象
        System.out.println("修改后卖出的委托对象====>>>" + sellEntrust);

        //修改卖出委托 数据库信息
        updateEntrust(sellEntrust);

                    /*
                    ==========2. 修改持仓表信息==========
                     */
        //1. 创建买入持仓表的对象
        int stockPosUserid = entrust1.getStockEntrustUserid();              // 用户 id
        String stockPosCode = entrust1.getStockEntrustCode();                // 股票代码
        String stockPosCompany = entrust1.getStockEntrustCompany();          // 股票名称
        int stockPosTradblance = entrust1.getStockEntrustTransnum();         // 股票股数(剩余多少股)
        int stockPosKyblance = entrust1.getStockEntrustTransnum();           // 可用股数(可以使用多少股)
        int stockPosDjblance = 0;                                            // 冻结股数
        BigDecimal stockPosMoney = new BigDecimal(entrust1.getStockEntrustMoney().toString());
        //BigDecimal stockPosMoney = new BigDecimal(jsonArray.getJSONObject(i).get("stockEntrustMoney").toString());
        POS pos = new POS(null, stockPosUserid, stockPosCode, stockPosCompany, stockPosTradblance, stockPosKyblance, stockPosDjblance, stockPosMoney);


        //1. (买入委托)判断 持仓表中是否有该股票信息   若有 修改信息  若没有 添加持仓表
        salePos(entrust1, pos);

        //2. (卖出委托)在持仓中将 冻结数量 - 委托数量 ; 股票数量 - 委托数量
        POS onePos = tradingClient.getOnePos(entrust1.getStockEntrustCode(), sellEntrust.getStockEntrustUserid());             //得到卖出的持仓对象
        System.out.println("修改前卖出的持仓对象===>> = " + onePos);
        onePos.setStockPosDjblance(onePos.getStockPosDjblance() - canSellNum);         //持仓表的冻结金额 - 卖出委托数量(成交数量)
        onePos.setStockPosTradblance(onePos.getStockPosTradblance() - canSellNum);     //持仓表的股票数 - 卖出的委托数(成交数量)

        //(测试) 修改后的 卖出委托持仓中的对象
        System.out.println("修改后卖出的持仓对象====>>>" + onePos);

        //修改卖出持仓 数据库信息
        updatePos(onePos);

                    /*
                    ==========3. 修改成交表信息==========
                     */

        //1. 将 买入委托 加入成交表中

        //得到 买入的成交对象
        Deal deal = new Deal(null,
                stockPosUserid,
                entrust1.getStockEntrustCode(),
                stockPosCompany,
                "买入",
                entrust1.getStockEntrustMoney(),
                new SimpleDateFormat("yyy-MM-dd HH:mm:ss.SSS").format(new Timestamp(System.currentTimeMillis())),
                "BtB" + new SimpleDateFormat("yyyMMddHHmmssSSS").format(new Timestamp(System.currentTimeMillis()))
        );

        // 将成交对象插入数据库中
        ResultBean resultBean1 = addDeal(deal);

        //2. 将卖出委托 加入成交表中

        //(测试) 卖出委托用户id
        System.out.println("sellEntrustUserid = " + sellEntrustUserid);

        //得到 卖出的成交对象
        Deal deal1 = new Deal(null,
                sellEntrustUserid,
                stockPosCode,
                stockPosCompany,
                "卖出",
                sellEntrustMoney,
                new SimpleDateFormat("yyy-MM-dd HH:mm:ss.SSS").format(new Timestamp(System.currentTimeMillis())),
                "StS" + new SimpleDateFormat("yyyMMddHHmmssSSS").format(new Timestamp(System.currentTimeMillis()))
        );

        // 将成交对象插入数据库中
        ResultBean resultBean2 = addDeal(deal1);
          /*
                   ======== 用户 金额 的修改 ======
                     */
        // 卖出用户的id
        Integer sellID = sellEntrust.getStockEntrustUserid();
        // 卖出的数量
        String s = canSellNum1.toString();
        BigDecimal sellNum = new BigDecimal(s);
        // 卖出的委托价格
        BigDecimal stockEntrustMoney1 = sellEntrust.getStockEntrustMoney();
        //总金额
        BigDecimal sumBalance = sellNum.multiply(stockEntrustMoney1);
        // 增加金额的方法
        topup(sellID,sumBalance);


        /*
         * ======== 修改 买卖盘信息 =======
         * */
        //买盘的对象
        StockBuyOrSale buyBos = selectBos(entrust1);
        //修改买盘的数量
        buyBos.setStockBSQuantity(buyBos.getStockBSQuantity()-canSellNum);
        //修改数据库信息
        updateBos(buyBos);

        //买盘的对象
        StockBuyOrSale sellBos = selectBos(sellEntrust);
        //修改买盘的数量
        sellBos.setStockBSQuantity(buyBos.getStockBSQuantity()-canSellNum);
        //修改数据库信息
        updateBos(sellBos);


        // 7. 判断是否成功
        if (resultBean1.getCode() == 1 && resultBean2.getCode() == 1) {
            r1 = new ResultBean(1, "交易成功!", "成交完成!");
        } else {
            r1 = new ResultBean(0, "交易失败!", "成交失败!");
        }


    }

    //11. 当买入 等于 卖出
    public ResultBean buyEqualSell(Entrust entrust1, Entrust sellEntrust, int sellEntrustUserid, BigDecimal sellEntrustMoney, ResultBean r1) {
        System.out.println("当买入等于卖出是的Entrust==>>" + entrust1);
        //卖出委托剩余可交易的数量
        int canSellNum = sellEntrust.getStockEntrustNum() - sellEntrust.getStockEntrustTransnum();
        Integer canSellNum1 = sellEntrust.getStockEntrustNum() - sellEntrust.getStockEntrustTransnum();
        //买入委托剩余可交易的数量
        int canBuyNum = entrust1.getStockEntrustNum() - entrust1.getStockEntrustTransnum();
        Integer canBuyNum1 = entrust1.getStockEntrustNum() - entrust1.getStockEntrustTransnum();
        /*
        1.修改委托表信息
         */
        //1. 将买入的状态改成全部成交
        entrust1.setStockEntrustStatus("全部成交");
        //2. 将买入的成交数量 改成 买入委托数量
        entrust1.setStockEntrustTransnum(canBuyNum + entrust1.getStockEntrustTransnum());
        //(测试用) 修改后的 买入委托对象
        System.out.println("修改后买入的委托对象====>>>" + entrust1);

        // 修改买入委托数据库信息
        updateEntrust(entrust1);

        //3. 将卖出的状态改成全部成交
        sellEntrust.setStockEntrustStatus("全部成交");

        //4. 将卖出的成交数量 改成 买入委托数量
        sellEntrust.setStockEntrustTransnum(canBuyNum + sellEntrust.getStockEntrustTransnum());

        //(测试用) 修改后的 卖出委托对象
        System.out.println("修改后卖出的委托对象====>>>" + sellEntrust);

        //修改卖出委托 数据库信息
        updateEntrust(sellEntrust);

        /*
        2.修改持仓表信息
         */

        //1. 创建持仓表的对象
        int stockPosUserid = entrust1.getStockEntrustUserid();              // 用户 id
        String stockPosCode = entrust1.getStockEntrustCode();                // 股票代码
        String stockPosCompany = entrust1.getStockEntrustCompany();          // 股票名称
        int stockPosTradblance = entrust1.getStockEntrustTransnum();         // 股票股数(剩余多少股)
        int stockPosKyblance = entrust1.getStockEntrustNum();                // 可用股数(可以使用多少股)
        int stockPosDjblance = 0;                                            // 冻结股数
        BigDecimal stockPosMoney = new BigDecimal(entrust1.getStockEntrustMoney().toString());
        //BigDecimal stockPosMoney = new BigDecimal(jsonArray.getJSONObject(i).get("stockEntrustMoney").toString());
        POS pos = new POS(null, stockPosUserid, stockPosCode, stockPosCompany, stockPosTradblance, stockPosKyblance, stockPosDjblance, stockPosMoney);


        //3. (买入委托)判断 持仓表中是否有该股票信息   若有 修改信息  若没有 添加持仓表
        salePos(entrust1, pos);

        //4. (卖出委托)在持仓中将 冻结数量 - 委托数量 ; 股票数量 - 委托数量
        POS onePos = tradingClient.getOnePos(entrust1.getStockEntrustCode(), sellEntrust.getStockEntrustUserid());             //得到卖出的持仓对象
        System.out.println("修改前卖出的持仓对象===>> = " + onePos);
        onePos.setStockPosDjblance(onePos.getStockPosDjblance() - canBuyNum);         //持仓表的冻结金额 - 买入委托数量(成交数量)
        onePos.setStockPosTradblance(onePos.getStockPosTradblance() - canBuyNum);     //持仓表的股票数 - 买入的委托数(成交数量)

        //(测试) 修改后的 卖出委托持仓中的对象
        System.out.println("修改后卖出的持仓对象====>>>" + onePos);

        //修改卖出持仓 数据库信息
        updatePos(onePos);

        /*
        3.修改成交表信息
         */
        //1. 将 买入委托 加入成交表中

        //得到 卖出的成交对象
        Deal deal = new Deal(null,
                stockPosUserid,
                entrust1.getStockEntrustCode(),
                stockPosCompany,
                "买入",
                entrust1.getStockEntrustMoney(),
                new SimpleDateFormat("yyy-MM-dd HH:mm:ss.SSS").format(new Timestamp(System.currentTimeMillis())),
                "BtB" + new SimpleDateFormat("yyyMMddHHmmssSSS").format(new Timestamp(System.currentTimeMillis()))
        );

        // 将成交对象插入数据库中
        ResultBean resultBean1 = addDeal(deal);

        //2. 将卖出委托 加入成交表中

        //卖出委托的 用户id

        //(测试) 卖出委托用户id
        System.out.println("sellEntrustUserid = " + sellEntrustUserid);

        //得到 卖出的成交对象
        Deal deal1 = new Deal(null,
                sellEntrustUserid,
                stockPosCode,
                stockPosCompany,
                "卖出",
                sellEntrustMoney,
                new SimpleDateFormat("yyy-MM-dd HH:mm:ss.SSS").format(new Timestamp(System.currentTimeMillis())),
                "StS" + new SimpleDateFormat("yyyMMddHHmmssSSS").format(new Timestamp(System.currentTimeMillis()))
        );

        // 将成交对象插入数据库中
        ResultBean resultBean2 = addDeal(deal1);
         /*
                   ======== 用户 金额 的修改 ======
                     */
        // 卖出用户的id
        Integer sellID = sellEntrust.getStockEntrustUserid();
        // 卖出的数量
        String s = canBuyNum1.toString();
        BigDecimal sellNum = new BigDecimal(s);
        // 卖出的委托价格
        BigDecimal stockEntrustMoney1 = sellEntrust.getStockEntrustMoney();
        //总金额
        BigDecimal sumBalance = sellNum.multiply(stockEntrustMoney1);
        // 增加金额的方法
        topup(sellID,sumBalance);


        /*
         * ======== 修改 买卖盘信息 =======
         * */
        //买盘的对象
        StockBuyOrSale buyBos = selectBos(entrust1);
        //修改买盘的数量
        buyBos.setStockBSQuantity(buyBos.getStockBSQuantity()-canBuyNum);
        //修改数据库信息
        updateBos(buyBos);

        //买盘的对象
        StockBuyOrSale sellBos = selectBos(sellEntrust);
        //修改买盘的数量
        sellBos.setStockBSQuantity(buyBos.getStockBSQuantity()-canBuyNum);
        //修改数据库信息
        updateBos(sellBos);


        // 7. 判断是否成功
        if (resultBean1.getCode() == 1 && resultBean2.getCode() == 1) {
            r1 = new ResultBean(1, "交易成功!", "成交完成!");
        } else {
            r1 = new ResultBean(0, "交易失败!", "成交失败!");
        }

        return r1;

    }

    //12. 判断 持仓表中是否有该股票信息   若有 修改信息  若没有 添加持仓表
    public void salePos(Entrust entrust, POS pos) {
        if (tradingClient.getOnePos(entrust.getStockEntrustCode(), entrust.getStockEntrustUserid()) == null) {
            // 将买入的委托信息 加入 持仓表中
            // 存入持仓中
            addPOS(pos);
        } else {
            //将股票的股数 + 买入的委托数量
            POS onePos = tradingClient.getOnePos(entrust.getStockEntrustCode(), entrust.getStockEntrustUserid());
            onePos.setStockPosTradblance(onePos.getStockPosTradblance() + entrust.getStockEntrustTransnum());
            onePos.setStockPosKyblance(onePos.getStockPosKyblance() + entrust.getStockEntrustTransnum());
            updatePos(onePos);
        }
    }

    //13. 修改委托表信息
    @RequestMapping(value = "/buy/updateEntrust")
    public Integer updateEntrust(@RequestBody(required = false) Entrust entrust) {
        return tradingClient.updateEntrust(entrust);
    }

    //14. 修改持仓表信息
    @RequestMapping(value = "/buy/updatePos")
    public Integer updatePos(@RequestBody(required = false) POS pos) {
        return tradingClient.updatePos(pos);
    }

    //15. 通过合同编号查询委托信息
    @RequestMapping(value = "/buy/selectEntrustByContractID")
    public Entrust selectEntrustByContractID(@RequestParam("contractID") String contractID) {
        return tradingClient.selectEntrustByContractID(contractID);
    }

    //16. (用户账户)余额增加
    @RequestMapping(value = "/user/topup")
    public ResultBean topup(@RequestParam("userid") int userid,@RequestParam("balance") BigDecimal balance){
        ResultBean topup = userClient.topup(userid, balance);
        return topup;
    }

    //17. (用户账户)余额减少
    @RequestMapping(value = "/user/withdraw")
    public ResultBean withdraw(@RequestParam("userid") int userid,@RequestParam("balance") BigDecimal balance){
        ResultBean withdraw = userClient.withdraw(userid, balance);
        return withdraw;
    }

     //18. 通过用户id 查询银行卡信息
    @RequestMapping("/user/selectBankCardByUserID")
    public Bankcard selectBankCardByUserID(@RequestParam(value = "userid" ,required = false) int userid){
        return userClient.selectBankCardByUserID(userid);
    }

     //19. 通过用户ID 查询用户信息
    @RequestMapping(value = "/user/selectTUserByUserID")
    public TUser selectTUserByUserID(@RequestParam(value = "userid" ,required = false) int userid){
        return userClient.selectTUserByUserID(userid);
    }

     //20. 通过 委托查询 买卖盘信息
    @RequestMapping(value = "/buy/selectBos")
    public StockBuyOrSale selectBos(@RequestBody Entrust entrust){
        return tradingClient.selectBos(entrust);
    }


     //21. 修改买卖盘信息
    @RequestMapping("/buy/updateBos")
    public ResultBean updateBos(@RequestBody StockBuyOrSale stockBuyOrSale){
        return tradingClient.updateBos(stockBuyOrSale);
    }


}
